package com.csdn.leon.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.csdn.leon.activity.BlogCloumnListActivity.ParserTask;
import com.csdn.leon.adapter.CloumnAdapter;
import com.csdn.leon.adapter.HostBlogAdapter;
import com.csdn.leon.base.BaseActivity;
import com.csdn.leon.cache.AsycTaskUtil;
import com.csdn.leon.cache.AsycTaskUtil.TaskCompletdListener;
import com.csdn.leon.dao.DBDao;
import com.csdn.leon.db.DBUtil;
import com.csdn.leon.model.BlogModel;
import com.csdn.leon.model.CloumnModel;
import com.csdn.leon.model.CommonList;
import com.csdn.leon.model.Person;
import com.csdn.leon.net.CSDNapi;
import com.csdn.leon.util.Constants;
import com.csdn.leon.util.JsoupUtil;
import com.csdn.leon.util.ListHelpUtil;
import com.csdn.leon.util.SPUtils;
import com.csdn.leon.util.StringUtils;
import com.csdn.leon.util.URLUtil;
import com.csdn.leon.view.CustomButton;
import com.csdn.leon.view.dialog.CustomDialog;
import com.csdn.leon.view.dialog.DialogHelper;
import com.csdn.leon.view.dialog.CustomDialog.DialogListener;
import com.csdn.leon.view.swipyrefreshlayout.SwipyRefreshLayout;
import com.csdn.leon.view.swipyrefreshlayout.SwipyRefreshLayoutDirection;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.csdn.leon.base.R;

/**
 * 
 * 类名称 : BlogHostActivity 功能描述: 博主信息及. 修改记录: 修改者: lenovo 修改日期: 2015年6月20日 修改内容:
 * TODO(描述本次修改内容). 版本信息: V1.0
 */
@SuppressLint("ResourceAsColor")
public class BlogHostActivity extends BaseActivity implements
		SwipyRefreshLayout.OnRefreshListener, OnClickListener,
		OnItemClickListener {
	private static final String TAG = BlogHostActivity.class.getSimpleName();
	private ListView mListView;
	private SwipyRefreshLayout mSwipyRefreshLayout;
	private TextView leftTv;
	private ImageView leftImg;
	private TextView middleTv;
	private ImageView host_img;
	private TextView host_number;
	private TextView host_name;
	private Button host_watch;
	private String url;
	private String username;
	protected int mCurrentPage = 1;
	private ParserTask mParserTask;
	private List<BlogModel> list;
	private Person person;
	private View headView;
	private LayoutInflater inflater;
	private HostBlogAdapter hostAdapter;
	private DisplayImageOptions options;

	@SuppressLint("ResourceAsColor")
	private Handler hostHandle = new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
			host_watch.setVisibility(View.VISIBLE);
			if(msg.what == 0){
				host_watch.setBackgroundResource(R.drawable.comment_bg_selected);
				host_watch.setTextColor(R.color.white);
				host_watch.setText("正在关注");
			}else if(msg.what == 1){
				host_watch.setBackgroundResource(R.drawable.comment_bg_selector);
				host_watch.setTextColor(R.color.btn_bg_color);
				host_watch.setText("添加关注");
				
			}
			super.handleMessage(msg);
		}
	};
	
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_host_layout);
		inflater = LayoutInflater.from(this);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.csdn)
				.showImageForEmptyUri(R.drawable.csdn)
				.showImageOnFail(R.drawable.csdn).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(100)).build();
		initLayout();
//		Intent intent1 = new Intent();  //Itent就是我们要发送的内容
//        intent1.setAction("COM.DIALOG.SEARCH");   //设置你这个广播的action，只有和这个action一样的接受者才能接受者才能接收广播
//        sendBroadcast(intent1);   //发送广播
	}

	private void initLayout() {
		username = this.getIntent().getStringExtra("username").toString();
		hostAdapter = new HostBlogAdapter(this);
		mListView = (ListView) findViewById(R.id.listview_host);
		headView = inflater.inflate(R.layout.host_head_layout, null);
		host_number = (TextView) headView.findViewById(R.id.host_number);
		host_name = (TextView) headView.findViewById(R.id.host_username_tv);
		host_watch = (Button) headView.findViewById(R.id.host_watch);
		
		host_watch.setOnClickListener(this);
		mListView.addHeaderView(headView);
		mListView.setAdapter(hostAdapter);
		mListView.setOnItemClickListener(this);
		mSwipyRefreshLayout = (SwipyRefreshLayout) findViewById(R.id.swipyrefreshlayout_host);
		mSwipyRefreshLayout.setOnRefreshListener(this);
		leftTv = (TextView) findViewById(R.id.title_left_text);
		leftTv.setVisibility(View.GONE);
		leftImg = (ImageView) findViewById(R.id.title_left_img);
		leftImg.setVisibility(View.VISIBLE);
		leftImg.setImageResource(R.drawable.actionbar_back_icon_normal);
		leftImg.setOnClickListener(this);
		middleTv = (TextView) findViewById(R.id.title_middle_text);
		middleTv.setVisibility(View.VISIBLE);
		host_img = (ImageView) headView.findViewById(R.id.host_user_img);

		middleTv.setText(this.getResources().getText(
				R.string.title_middleleft_6));

		
		requestData(true);
	}

	//发送请求的handle
	TextHttpResponseHandler handle = new TextHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2,
				Throwable arg3) {
			hideWaitDialog();
			mSwipyRefreshLayout.setRefreshing(false);
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String s) {
			Log.w(TAG, s);
			executeParserTask(s);
		}
	};

	
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_img:
			finish();
			break;
		case R.id.host_watch:
			if(DBUtil.queryHost(BlogHostActivity.this, person.getUsername())){
				final CustomDialog dialog = DialogHelper.getCustomDialog(BlogHostActivity.this);
				dialog.show();
				dialog.setDialogListener(new DialogListener() {
					
					@Override
					public void isCancel(boolean flag) {
						dialog.hide();
						if(flag){
							if(DBUtil.deleteHost(BlogHostActivity.this, username)){
							Message msg = new Message();
							msg.what =1;
							hostHandle.sendMessage(msg);
							}
						}else{
						}
					}
				});
				Toast.makeText(BlogHostActivity.this, person.getUsername(), 1000).show();
			}else {
				if(DBUtil.insertHost(BlogHostActivity.this, person)){
					Message msg = new Message();
					msg.what =0;
					hostHandle.sendMessage(msg);
				}else{
					Toast.makeText(BlogHostActivity.this, "关注失败", 1000).show();
				}
			}
			break;
		}
	}

	/**
	 * Called when the
	 * {@link com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout}
	 * is in refresh mode. Just for example purpose.
	 */
	@Override
	public void onRefresh(SwipyRefreshLayoutDirection direction) {

		if (direction == SwipyRefreshLayoutDirection.TOP) {
			mCurrentPage = 1;
			sendRequestData(username, true);
		} else if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
			mCurrentPage++;
			sendRequestData(username, false);
		}
	}

	/***
	 * 获取列表数据
	 * 
	 * 
	 * @author leon
	 * 
	 * @return void
	 * @param refresh
	 */
	// 取新的数据
	protected void requestData(boolean refresh) {
		showWaitDialog();
		// String key = StringUtils.getCacheKey(TAG, username, mCurrentPage);
		// if (AsycTaskUtil.getInstance().isReadCache(BlogCloumnActivity.this,
		// TAG, username, mCurrentPage)
		// && refresh) {
		// AsycTaskUtil.getInstance().readCloumnModelData(
		// BlogCloumnActivity.this, key);
		// } else {
		sendRequestData(username, refresh);
		// }
	}

	protected void sendRequestData(String username, boolean flag) {
		if (flag) {
			url = URLUtil.getHostBlogListURL(username);
		} else {
			url = URLUtil.getHostBlogListURL(username,
					String.valueOf(mCurrentPage));
		}
		CSDNapi.getBlogList(url, handle);
	}

	private void executeParserTask(String data) {
		cancelParserTask();
		mParserTask = new ParserTask(data);
		mParserTask.execute();
	}

	private void cancelParserTask() {
		if (mParserTask != null) {
			mParserTask.cancel(true);
			mParserTask = null;
		}
	}

	class ParserTask extends AsyncTask<Void, Void, String> {
		private final String reponseData;
		private boolean parserError;
		private List<BlogModel> list;

		public ParserTask(String data) {
			this.reponseData = data;
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				CommonList<CloumnModel> commonList = ListHelpUtil
						.paraseCloumnModelToList(reponseData);
				list = (List<BlogModel>) JsoupUtil.getHostBlogList(reponseData)
						.get("list");
				person = (Person) JsoupUtil.getHostBlogList(reponseData).get(
						"person");
			
				if(DBUtil.queryHost(BlogHostActivity.this, person.getUsername())){
					Message msg = new Message();
					msg.what = 0;
					hostHandle.sendMessage(msg);
				}else{
					Message msg = new Message();
					msg.what = 1;
					hostHandle.sendMessage(msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
				parserError = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			executeAdapterData(list);
		}
	}

	private void executeAdapterData(List<BlogModel> list) {
		mSwipyRefreshLayout.setRefreshing(false);
		if (list != null) {
			if (mCurrentPage == 1) {
				hostAdapter.setList(list);
			} else {
				hostAdapter.addAllList(list);
			}
		} else {
			list = new ArrayList<BlogModel>();
			hostAdapter.setList(list);
		}
		if((boolean) SPUtils.get(BlogHostActivity.this, Constants.KEY_LOAD_IMAGE, true)){
			ImageLoader.getInstance().displayImage(person.getUserface(), host_img,
					options);
			}
		
		host_name.setText(person.getUsername());
		host_number.setText(person.getRank().replace(" ", ""));
		// if(host_watch.isEnabled()){
		// host_watch.setEnabled(true);
		// }
		hideWaitDialog();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		BlogModel blogModel = hostAdapter.getList().get(position);
		Intent intent = new Intent(this, BlogDetailActivity.class);
		String url = blogModel.getLink();
		intent.putExtra("blog_url",
				"http://blog.csdn.net" + blogModel.getLink());
		startActivity(intent);

	}

}
